<template>
	<view class="root">
		<notice-bar
			backgroundColor="#fbf9ca"
			color="#ff5500"
			:showIcon="true"
			:showClose="true"
			:scrollable="true"
			:single="true"
			:speed="50"
			:text="userInfo.notice"
		/>
		<view class="header">
			<view
				v-for="(nav, index) in navigation"
				:key="index"
				hover-class="tap-hover"
				hover-stay-time="100"
				:class="['navigation', { before: index && false }]"
				@click="switchNav(index)"
			>
				<label :class="{ active: navIndex === index }">
					{{ nav }}
				</label>
			</view>
		</view>
		<text v-if="driver_id" class="scanCode-tips color-459184">
			你正在通过扫码快速下单
		</text>

		<view v-if="navIndex === 0" class="in-city">
			<map
				id="map"
				:longitude="startPoint.longitude"
				:latitude="startPoint.latitude"
				:show-location="true"
				:enable-traffic="true"
				:enable-3D="true"
			/>
			<view
				@click="callSOS"
				hover-class="tap-hover"
				hover-stay-time="50"
				class="sos"
			>
				<image mode="aspectFit" src="/static/images/icon-sos.png" />
				<text>求救报警</text>
			</view>
			<block v-if="userInfo.identity">
				<label class="enableOrder">
					<switch
						color="#5487e5"
						@change="switchGetOrderState"
						:checked="getOrderState.checked"
						:disabled="getOrderState.hasOrder"
					/>
					<text>
						已{{ getOrderState.checked ? "开启" : "关闭" }}接单
					</text>
				</label>

				<view class="orders">
					<view
						v-if="getOrderState.hasOrder"
						hover-class="tap-hover"
						hover-stay-time="100"
						class="has-order"
						@click="alreadyOrder(0)"
					>
						<text class="has-order">已有订单正在进行中</text>
						<image
							class="icon-more"
							src="/static/images/icon-more.png"
						/>
					</view>

					<block v-else-if="journeyOrder.id">
						<label class="overview">
							<image
								class="icon-location_black"
								src="/static/images/icon-location_black.png"
							/>
							<text class="tips">{{ journeyOrder.tips }}</text>
						</label>

						<view class="location-info">
							<label
								v-if="journeyOrder.startPoint"
								class="start-point"
							>
								<view>
									<text
										v-if="journeyOrder.startPoint.name"
										class="name"
									>
										{{ journeyOrder.startPoint.name }}
									</text>
									<text
										v-if="journeyOrder.startPoint.address"
										class="address"
									>
										{{ journeyOrder.startPoint.address }}
									</text>
								</view>
							</label>
							<label
								v-if="journeyOrder.destination"
								class="destination"
							>
								<view>
									<text
										v-if="journeyOrder.destination.name"
										class="name"
									>
										{{ journeyOrder.destination.name }}
									</text>
									<text
										v-if="journeyOrder.destination.address"
										class="address"
									>
										{{ journeyOrder.destination.address }}
									</text>
								</view>
							</label>
						</view>

						<button
							:plain="true"
							hover-class="tap-hover"
							class="btn-order"
							@click="receiveOrder"
						>
							<text>{{ countdown }}s</text>
							<text>接单</text>
						</button>
						<text
							v-if="journeyOrder.orderTypeName"
							class="order-type"
						>
							{{ journeyOrder.orderTypeName }}
						</text>
					</block>

					<text class="no-order" v-else>
						{{
							getOrderState.checked
								? "正在搜索附近乘客 ..."
								: "你已关闭接单状态 ..."
						}}
					</text>
				</view>
			</block>
			<block v-else>
				<view
					hover-stay-time="50"
					hover-class="tap-hover"
					class="shake"
					@click="popupSwitch(1, 'shake')"
				>
					<image
						mode="aspectFit"
						src="/static/images/icon-shake.png"
					/>
					<text>摇一摇</text>
				</view>
				<view class="choose-position">
					<view class="tips">
						<label v-if="journey" class="journey">
							<image
								class="icon-speaker"
								src="/static/images/icon-speaker.png"
							/>
							<text>{{ journey }}</text>
						</label>
						<label class="notice">
							<image
								class="icon-medical"
								src="/static/images/icon-medical.png"
							/>
							<text class="color-ef3e4c">
								请您务必佩戴口罩出行
							</text>
						</label>
					</view>

					<navigator hover-class="tap-hover" url="invite">
						<image
							class="pic-inCity"
							src="/static/images/pic-inCity.png"
						/>
					</navigator>

					<view class="choose-location">
						<label @click="chooseLocation(0)" class="start-point">
							<text>你将从</text>
							<text class="point">{{ startPoint.name }}</text>
							<text>上车</text>
						</label>
						<input
							@click="chooseLocation(1)"
							v-model="destination.name"
							class="destination input"
							placeholder="选择目的地"
							placeholder-style="font-size: 28rpx;"
							disabled
						/>
					</view>
					<text v-if="budget.length" class="fee color-ff4a5b">
						<text> 预计费用: {{ budget[carIndex].fee }}元</text>
						<text>
							{{
								budget[carIndex].discount
									? `（优惠券抵扣 ${budget[carIndex].discount} 元）`
									: ""
							}}
						</text>
					</text>
					<button
						@click="confirmCall"
						:disabled="!destination.name"
						hover-class="tap-hover"
						class="btn-confirm"
					>
						{{ driver_id ? "立即上车" : "确认呼叫" }}
					</button>
				</view>

				<popup ref="shake" @change="popupChange($event, 'shake')">
					<view class="shake-wrapper">
						<view class="title">
							<image
								mode="aspectFill"
								src="/static/images/bg-shake.png"
							/>
							<text>摇一摇打车</text>
						</view>
						<view class="content">
							<image
								class="pic-shake"
								src="/static/images/pic-shake.png"
							/>
							<view class="describe">
								<text class="introduction">左右摇动手机</text>
								<text class="waiting">等待司机接单</text>
							</view>
						</view>
						<button
							@click="shake"
							hover-class="tap-hover"
							class="btn-shake"
						>
							摇一摇
						</button>
					</view>
				</popup>
			</block>
		</view>

		<view class="intercity" v-if="navIndex === 1">
			<view class="routes">
				<label class="place green">
					<view
						hover-class="tap-hover"
						@click="chooseLocation(0)"
						class="location"
					>
						<text class="site ellipsis">
							{{ routes[routeIndex].startPoint }}
						</text>
						<text class="explain">出发地</text>
					</view>
				</label>

				<image
					@click="popupSwitch(1, 'routes')"
					class="icon-transform"
					src="/static/images/icon-transform.png"
				/>

				<label class="place blue">
					<view
						hover-class="tap-hover"
						@click="chooseLocation(1)"
						class="location"
					>
						<text class="site ellipsis">
							{{ routes[routeIndex].destination }}
						</text>
						<text class="explain"> 目的地 </text>
					</view>
				</label>
			</view>
			<view v-if="!userInfo.identity" class="choose-location">
				<label @click="chooseLocation(0)" class="start-point">
					<text>你将从</text>
					<text class="point">{{ startPoint.name }}</text>
					<text>上车</text>
				</label>
				<input
					@click="chooseLocation(1)"
					v-model="destination.name"
					class="destination input"
					placeholder="选择目的地城市详细地址"
					placeholder-style="font-size: 28rpx;"
					disabled
				/>
			</view>

			<view class="options">
				<view
					v-for="option in options"
					:key="option.title"
					class="option"
				>
					<text class="title">{{ option.title }}</text>
					<text v-if="option.el == 'text'">
						{{ option.content }}
					</text>
					<text v-if="option.el == 'price'" class="color-ff4a5b">
						{{ routes[routeIndex].price }}元
					</text>
					<view v-if="option.el == 'view'" class="number">
						<view
							hover-class="tap-hover"
							hover-stay-time="100"
							@click="calc(0)"
							class="reduce"
						/>
						<input
							class="num"
							:value="`${model[option.model]} 人`"
							disabled
						/>
						<view
							hover-class="tap-hover"
							hover-stay-time="100"
							@click="calc(1)"
							class="plus"
						/>
					</view>

					<input
						v-if="option.el == 'input'"
						:type="option.type"
						maxlength="11"
						class="input"
						v-model="model[option.model]"
						placeholder-style="color: #999;"
						:placeholder="option.placeholder"
					/>

					<block v-if="option.el == 'picker'">
						<picker
							:disabled="isRightNow && option.model === 'time'"
							class="time"
							mode="multiSelector"
							:range="times"
							@change="pickerTime"
						>
							<text>{{ model[option.model] }}</text>
						</picker>

						<label>
							<switch
								type="checkbox"
								@change="rightNow"
								color="#5487e5"
								:checked="isRightNow"
							/>
							<text>即时出发</text>
						</label>
					</block>
				</view>
			</view>

			<button @click="takeCar" hover-class="tap-hover" class="btn-start">
				{{
					userInfo.identity
						? "开始接单"
						: driver_id
						? "立即上车"
						: "我要叫车"
				}}
			</button>

			<popup ref="routes" @change="popupChange">
				<view class="routes-popup">
					<label class="search">
						<image
							class="icon-search"
							src="/static/images/icon-search.png"
						/>
						<input
							@input="searchRoutes"
							class="input"
							:value="routeKeywords"
							placeholder="请输入地点搜索"
						/>
					</label>

					<label class="title">
						<text>往返路线选择</text>
						<text>|</text>
						<text>实际价格</text>
					</label>

					<scroll-view scroll-y class="options">
						<view
							hover-stay-time="100"
							hover-class="tap-hover"
							v-for="(item, index) in routes"
							:key="index"
							class="option"
							@click="chooseRoute(index)"
						>
							<label class="routes-site">
								<text class="site">
									{{ item.startPoint }}
								</text>
								<image
									class="icon-transform_blue"
									src="/static/images/icon-transform_blue.png"
								/>
								<text class="site">{{ item.destination }}</text>
							</label>
							<text class="price">{{ item.price }}元</text>
						</view>
					</scroll-view>
					<text class="tips">
						温馨提示：3公里以内20元，超出三公里按照每公里5元收费
					</text>
				</view>
			</popup>
		</view>

		<popup ref="proclamation" @change="popupChange" :maskClick="false">
			<image
				@click="receive"
				class="icon-proclamation"
				mode="widthFix"
				src="/static/images/icon-proclamation.png"
			/>
			<image
				@click="popupSwitch(0, 'proclamation')"
				class="icon-close"
				src="/static/images/icon-close.png"
			/>
		</popup>
	</view>
</template>

<script lang="ts">
	import Vue from "vue";
	import Component from "vue-class-component";
	import popup from "@/components/popup.vue";
	import noticeBar from "@/components/notice-bar.vue";
	import { UserInfo, Route, JourneyOrder } from "@/common/api.d";
	import { formatDate, formatEveryDay, Storage } from "@/libs/utils";
	const QQMapWX = require("@/libs/qqmap-wx-jssdk.min");

	type Location = {
		name: string;
		address: string;
		longitude: number;
		latitude: number;
		city?: string;
		district?: string;
	};

	let qqMapSdk: any,
		routes: Route[],
		timers: { [key: string]: number } = {},
		flag: boolean = false;

	let shakeInfo = {
		openFlag: true, // 是否开启摇一摇
		shakeSpeed: 110, //设置阈值,越小越灵敏
		lastTime: 0, //此变量用来记录上次摇动的时间
		x: 0,
		y: 0,
		z: 0,
		lastX: 0,
		lastY: 0,
		lastZ: 0, //分别记录对应 x、y、z 三轴的数值和上次的数值
	};

	@Component({
		components: { popup, noticeBar },
		watch: {
			isRightNow(val) {
				this.$data.model.time = val
					? formatDate(Date.now(), "M月D日 h:m")
					: `${this.$data.times[0][0]} ${this.$data.times[1][0]}`;
			},
		},
	})
	export default class Home extends Vue {
		navIndex: number = 0;
		routeIndex: number = 0;
		isRightNow: boolean | null = null;

		times: string[][] = [[]];

		userInfo: UserInfo | AnyObject = {};

		getOrderState: {
			checked: boolean;
			hasOrder: boolean;
			orderInfo: AnyObject | null;
			statusPages: string[];
		} = {
			checked: false,
			hasOrder: false,
			orderInfo: null,
			statusPages: [],
		};

		navigation: string[] = ["城内打车", "城际拼车", "充电", "救援"];

		startPoint: Location = {
			name: "获取位置中...",
			address: "",
			longitude: 104.065901,
			latitude: 30.657372,
		};
		destination: Location = {
			name: "",
			address: "",
			longitude: 0,
			latitude: 0,
		};
		model: {
			numberOfPeople: number;
			phoneNumber: string;
			time: string;
			remarks: string;
			[props: string]: string | number;
		} = {
			numberOfPeople: 1,
			phoneNumber: "",
			time: "00:00",
			remarks: "",
		};
		routes: Array<Route> = [
			{
				startPoint: "",
				destination: "",
				price: "",
			},
		];

		routeKeywords: string = "";

		options: Array<AnyObject> = [
			{
				title: "价格",
				el: "price",
			},
			{
				title: "选择人数",
				model: "numberOfPeople",
				el: "view",
			},
			{
				title: "预约时间",
				model: "time",
				placeholder: "请输入他人手机号码",
				el: "picker",
			},
		];
		budget: { fee: string; discount: string }[] = [];
		carIndex: number = 0;
		journey: string = "";
		journeyOrder: JourneyOrder | AnyObject = {};
		countdown: number = 10;
		driver_id: number = 0;

		private onReady(): void {
			this.userInfo?.is_coupon === 0 && this.popupSwitch(1, "proclamation");
			if (!+this.userInfo?.identity) {
				this.options.push(
					...[
						{
							title: "为他人叫车",
							placeholder: "请输入他人手机号码",
							model: "phoneNumber",
							type: "number",
							el: "input",
						},

						{
							title: "备注",
							model: "remarks",
							placeholder: "请输入备注内容",
							type: "text",
							el: "input",
						},
					]
				);
			}
			uni.setTabBarItem({
				index: 0,
				text: this.userInfo?.identity ? "接单大厅" : "首页",
			});
		}

		private async onLoad({
			user_id: parent_id,
			driver_id,
		}: AnyObject): Promise<void> {
			const now = new Date();

			this.times = [
				formatEveryDay(now, new Date(now.getTime() + 604800000), "M月D日"),
				this.userInfo?.identity
					? [
							"00:00",
							"03:00",
							"06:00",
							"09:00",
							"12:00",
							"15:00",
							"18:00",
							"21:00",
					  ]
					: [
							"00:00 - 02:00",
							"03:00 - 06:00",
							"06:00 - 09:00",
							"09:00 - 12:00",
							"12:00 - 15:00",
							"15:00 - 18:00",
							"18:00 - 21:00",
							"21:00 - 00:00",
					  ],
			];

			this.isRightNow = Boolean(driver_id);

			// #ifdef MP-WEIXIN
			qqMapSdk = new QQMapWX({
				key: "CLBBZ-SE6CJ-RWDF7-K6OYL-ARE5O-KQBRU",
			});

			const [, success]: any = await uni.getLocation({});

			if (!success) return;
			const { longitude, latitude } = success;
			qqMapSdk.reverseGeocoder({
				location: { longitude, latitude },
				success: ({ result }: any) => {
					this.startPoint = {
						name: result.address,
						longitude,
						latitude,
						address: result.address,
						city: result.ad_info.city,
						district: result.ad_info.district,
					};
				},
				fail() {
					uni.showToast({
						title: "位置获取失败",
						icon: "none",
					});
				},
			});
			// #endif

			this.driver_id = +driver_id || 0;

			parent_id && this.request.get("/api/bindParent", { parent_id });
		}

		private onShow() {
			this.request.get("/api/personalCenter").then(({ data }) => {
				Storage.update("userInfo", data);
				this.userInfo = Storage.get("userInfo");
			});

			flag = false;
			this.userInfo?.identity &&
				!this.navIndex &&
				this.getOrderState.checked &&
				this.scanPassenger();

			this.checkOrderStatus();

			shakeInfo.openFlag = true;
		}

		private onHide(): void {
			this.resetAsyncTask();
		}

		private onUnload(): void {
			this.resetAsyncTask();
		}

		public resetAsyncTask(): void {
			flag = true;
			this.countdown = 10;
			shakeInfo.openFlag = false;
			delete this.journeyOrder.id;
			uni.offAccelerometerChange((res) => console.log(res));
			Object.values(timers).forEach((timer) => clearInterval(timer));
		}

		public async shake(): Promise<void> {
			this.popupSwitch(0, "shake");
			uni.showToast({ title: "loading...", icon: "loading", mask: true });
			const [locationFail, locationResult]: any = await uni.getLocation({});

			if (locationFail) {
				uni.showToast({ title: locationFail.errMsg, icon: "none" });
				return;
			}

			const {
				longitude,
				latitude,
			} = locationResult as UniApp.GetLocationSuccess;

			qqMapSdk.reverseGeocoder({
				location: {
					longitude,
					latitude,
				},
				success: ({ result }: any) => {
					this.request
						.get("/api/yao", {
							address: result.address,
							name: result.address,
							longitude,
							latitude,
						})
						.then(({ data }) => {
							uni.hideToast();
							uni.navigateTo({
								url: `/pages/inCity?status=0&order_id=${data.order_id}`,
							});
						});
				},
				fail: () => uni.showToast({ title: "获取位置失败", icon: "none" }),
			});
		}

		public checkOrderStatus(): void {
			this.request.get("/api/checkOrder").then(({ data }) => {
				this.$set(this.getOrderState, "hasOrder", data.has_order);
				if (!data.has_order) return;
				this.$set(this.getOrderState, "checked", !data.has_order);

				this.getOrderState.orderInfo = data;
				this.getOrderState.statusPages = data.identity
					? [
							"orderHall?",
							"travel?status=1&",
							`travel?status=3&jiaoche_id=${data.now_jie}&`,
							"travel?status=5&",
					  ]
					: [
							data.takeCarMode === 1
								? "orderHall?"
								: "inCity?status=0&",
							data.takeCarMode === 1
								? `travel?status=2&jiaoche_id=${data.now_jie}&`
								: "inCity?status=1&",
							data.takeCarMode === 1
								? `travel?status=4&jiaoche_id=${data.now_jie}&`
								: "inCity?status=1&",
							"travel?status=6&",
							"travel?status=7&",
					  ];

				this.alreadyOrder();
			});
		}

		public callSOS(): void {
			uni.makePhoneCall({ phoneNumber: this.userInfo.sos });
		}

		public switchGetOrderState({ detail }: AnyObject): void {
			this.$set(this.getOrderState, "checked", detail.value);

			detail.value ? this.enableScanOrder() : this.resetAsyncTask();
		}

		public enableScanOrder(): void {
			flag = false;
			this.userInfo.identity &&
				this.getOrderState.checked &&
				this.scanPassenger();
		}

		public searchRoutes(e: any): void {
			this.routeKeywords = e.detail.value;
			const result = routes.filter(({ startPoint, destination }) =>
				`${startPoint} ${destination}`.includes(this.routeKeywords)
			);

			this.routes = result.length ? result : routes;
		}

		public confirmCall(): void {
			this.request
				.get("/api/jiaocheHandle", {
					carType: 2,
					address: this.startPoint.address,
					name: this.startPoint.name,
					latitude: this.startPoint.latitude,
					longitude: this.startPoint.longitude,

					end_address: this.destination.address,
					end_name: this.destination.name,
					end_latitude: this.destination.latitude,
					end_longitude: this.destination.longitude,

					siji_uid: this.driver_id,
				})
				.then(({ data }) => {
					uni.navigateTo({
						url: `/pages/inCity?status=0&order_id=${data.order_id}`,
					});
					this.driver_id = 0;
				})
				.catch(({ data }) => {
					this.getOrderState.orderInfo = data;
					this.getOrderState.statusPages = [
						"inCity?status=0&",
						"inCity?status=1&",
						`inCity?status=1&`,
						"travel?status=6&",
						"travel?status=7&",
					];
					this.alreadyOrder();
				});
		}

		public alreadyOrder(showModal: number = 1): void {
			const { orderInfo, statusPages } = this.getOrderState;
			if (!orderInfo) return;

			const toStatusPages = () =>
				uni.navigateTo({
					url: `/pages/${
						statusPages[
							this.userInfo.identity
								? orderInfo.status - 4
								: orderInfo.status
						]
					}order_id=${orderInfo.order_id}`,
					fail: ({ errMsg: title }) =>
						uni.showToast({ title, icon: "none" }),
				});

			showModal
				? uni.showModal({
						title: "提示",
						content: "你有一个正在进行中的订单，点击进入",
						success: ({ confirm }) => confirm && toStatusPages(),
				  })
				: toStatusPages();
		}

		public async chooseLocation(type: number): Promise<void> {
			if (this.userInfo.identity) return;
			const [, locationRes]: any = await uni.chooseLocation({});

			if (!locationRes) return;

			const {
				longitude,
				latitude,
				name,
				address,
			} = locationRes as UniApp.ChooseLocationSuccess;

			qqMapSdk.reverseGeocoder({
				location: { longitude, latitude },
				success: ({ result }: any) => {
					this[type ? "destination" : "startPoint"] = {
						name,
						longitude,
						latitude,
						address,
						city: result.ad_info.city,
						district: result.ad_info.district,
					};

					const {
						latitude: start_lat,
						longitude: start_lng,
					} = this.startPoint;

					const {
						latitude: end_lat,
						longitude: end_lng,
					} = this.destination;

					if (!end_lat || !end_lng) return;

					this.getRoutes();

					this.request
						.get("/api/cityJiaoche", {
							latitude: start_lat,
							longitude: start_lng,
							end_latitude: end_lat,
							end_longitude: end_lng,
						})
						.then(({ code, data, msg }) => {
							this.journey = data.journey;
							this.budget = data.carlist;
						});
				},
				fail() {
					uni.showToast({
						title: "位置获取失败",
						icon: "none",
					});
				},
			});
		}

		public chooseRoute(index: number): void {
			this.routeIndex = index;
			this.popupSwitch(0, "routes");
		}

		public pickerTime({ detail }: any): void {
			this.model.time = `${this.times[0][detail.value[0]]} ${
				this.times[1][detail.value[1]]
			}`;
		}

		public rightNow({ detail }: any): void {
			this.isRightNow = detail.value;
		}

		public calc(type: number): void {
			if (!type && this.model.numberOfPeople <= 1) {
				uni.showToast({ title: "不能再少了", icon: "none" });
				return;
			}

			if (type && this.model.numberOfPeople >= 6) {
				uni.showToast({ title: "不能再多了", icon: "none" });
				return;
			}

			type ? this.model.numberOfPeople++ : this.model.numberOfPeople--;
		}

		public takeCar(): void {
			const {
				request,
				userInfo: { phoneNumber, identity },
				routes,
				routeIndex,
				model,
				isRightNow,
				startPoint,
				destination,
				alreadyOrder,
				getOrderState,
				driver_id: siji_uid,
			} = this;

			if (!phoneNumber) {
				uni.showModal({
					title: "提示",
					content: "授权用户信息和绑定手机号码后体验更佳",
					confirmText: "去授权",
					success: ({ confirm }) =>
						confirm && uni.switchTab({ url: "my" }),
				});
				return;
			}

			if (!identity && !destination.name) {
				uni.showToast({ title: "请选择目的地位置", icon: "none" });
				return;
			}

			const options = identity
				? {
						route_id: routes[routeIndex].id,
						zuowei: model.numberOfPeople,
						go_now: Number(isRightNow),
						start_time: model.time,
				  }
				: {
						route_id: routes[routeIndex].id,

						address: startPoint.address,
						name: startPoint.name,
						latitude: startPoint.latitude,
						longitude: startPoint.longitude,

						end_address: destination.address,
						end_name: destination.name,
						end_latitude: destination.latitude,
						end_longitude: destination.longitude,

						number: model.numberOfPeople,
						go_now: Number(isRightNow),
						time: model.time,
						mobile: model.phoneNumber,
						carType: 1,

						siji_uid,
				  };

			request
				.post(
					`api/${identity ? "sijiPinHandle" : "jiaocheHandle"}`,
					options
				)
				.then(({ data }) => {
					uni.navigateTo({
						url: `orderHall?order_id=${data.order_id}`,
					});
					this.driver_id = 0;
				})
				.catch(({ data }) => {
					getOrderState.orderInfo = data;
					getOrderState.statusPages = identity
						? [
								"orderHall?",
								"travel?status=1&",
								`travel?status=3&jiaoche_id=${data.jiaoche_id}&`,
								"travel?status=5&",
						  ]
						: [
								"orderHall?",
								`travel?status=2&jiaoche_id=${data.jiaoche_id}&`,
								`travel?status=4&jiaoche_id=${data.jiaoche_id}&`,
								"travel?status=6&",
								"travel?status=7&",
						  ];
					alreadyOrder();
				});
		}

		public receive(): void {
			this.request.get("/api/linJuan").then((res) => {
				uni.showToast({
					title: "领取成功",
					success: () => this.popupSwitch(0, "proclamation"),
				});
				Storage.update("userInfo", { is_coupon: 1 });
			});
		}

		public async getRoutes(): Promise<void> {
			this.request
				.get(`/api/${this.userInfo.identity ? "sijiPin" : "jiaoche"}`, {
					latitude: this.startPoint.latitude,
					longitude: this.startPoint.longitude,
					district: this.startPoint.district,
					city: this.startPoint.city,

					end_latitude: this.destination.latitude,
					end_longitude: this.destination.longitude,
					end_district: this.destination.district,
					end_city: this.destination.city,
					siji_uid: this.driver_id,
				})
				.then(({ data }) => (routes = this.routes = data.routes))
				.catch(({ code, msg: content }) => {
					code === 2 &&
						uni.showModal({
							content,
							showCancel: false,
							success: ({ confirm }) =>
								confirm && uni.reLaunch({ url: "/pages/home" }),
						});
				});
		}

		public receiveOrderCountdown(): void {
			timers.orderTimer = setInterval(() => {
				this.countdown--;
				if (this.countdown <= 0) {
					this.journeyOrder = {};
					this.countdown = 10;
					this.scanPassenger();
					timers.orderTimer && clearInterval(timers.orderTimer);
				}
			}, 1000);
		}

		public receiveOrder(): void {
			this.request
				.get(`/api/citySijiJiedan?jiaoche_id=${this.journeyOrder.id}`)
				.then(({ data }) => {
					timers.orderTimer && clearInterval(timers.orderTimer);
					uni.navigateTo({
						url: `/pages/travel?status=1&order_id=${data.order_id}&jiaoche_id=${this.journeyOrder.id}`,
					});
				});
		}

		public async scanPassenger(): Promise<void> {
			const [locationFail, locationResult]: any = await uni.getLocation({});

			const {
				latitude,
				longitude,
			} = locationResult as UniApp.GetLocationSuccess;

			if (locationFail) {
				uni.showToast({ title: locationFail.errMsg, icon: "none" });
				return;
			}
			this.request
				.get("/api/citySijiWaitJiedan", { latitude, longitude })
				.then(({ data }) => {
					if (flag) return;
					if (!data) {
						timers.scanTimer = setTimeout(this.scanPassenger, 1000);
						return;
					}
					timers.scanTimer && clearTimeout(timers.scanTimer);
					this.journeyOrder = data;
					this.receiveOrderCountdown();
				})
				.catch(({ code }) => {
					if (code === 2) {
						this.checkOrderStatus();
						timers.scanTimer && clearTimeout(timers.scanTimer);
					}
				});
		}

		public async switchNav(index: number): Promise<void> {
			if (+index === this.navIndex) return;

			index && this.resetAsyncTask();

			switch (+index) {
				case 0:
					this.enableScanOrder();
					break;
				case 1:
					this.getRoutes();
					break;
				default:
					uni.showToast({
						title: "正在建设中, 敬请期待",
						icon: "none",
					});
					return;
			}

			this.navIndex = index;
		}

		public popupChange(
			{ show }: { show: boolean },
			refName: string | void
		): any {
			uni[show ? "hideTabBar" : "showTabBar"]({ animation: true });

			refName === "shake" &&
				(show
					? ((shakeInfo.openFlag = true),
					  uni.onAccelerometerChange((res) => {
							if (!shakeInfo.openFlag) return;

							const nowTime = new Date().getTime(); //记录当前时间
							//如果这次摇的时间距离上次摇的时间有一定间隔 才执行
							if (nowTime - shakeInfo.lastTime > 100) {
								const diffTime = nowTime - shakeInfo.lastTime; //记录时间段
								shakeInfo.lastTime = nowTime; //记录本次摇动时间
								shakeInfo.x = res.x; //获取 x 轴数值
								shakeInfo.y = res.y; //获取 y 轴数值
								shakeInfo.z = res.z; //获取 z 轴数值
								//计算摇一摇的速度
								const speed =
									(Math.abs(
										shakeInfo.x +
											shakeInfo.y +
											shakeInfo.z -
											shakeInfo.lastX -
											shakeInfo.lastY -
											shakeInfo.lastZ
									) /
										diffTime) *
									10000;
								//如果计算出来的摇一摇幅度足够大，那么认为用户摇一摇成功
								speed > shakeInfo.shakeSpeed && this.shake();
								//赋值，为下一次计算做准备
								shakeInfo.lastX = shakeInfo.x;
								shakeInfo.lastY = shakeInfo.y;
								shakeInfo.lastZ = shakeInfo.z;
							}
					  }))
					: ((shakeInfo.openFlag = false),
					  uni.offAccelerometerChange((res) => console.log(res))));
		}

		public popupSwitch(OnOff: 0 | 1, refName: string): void {
			(this.$refs[refName] as AnyObject)[OnOff ? "open" : "close"]();
		}
	}
</script>

<style>
	page {
		height: 100%;
	}
</style>
<style lang="scss" scoped>
	.root {
		flex: 1;
		> .header {
			flex-direction: row;
			justify-content: space-evenly;
			align-items: center;
			.navigation {
				color: #1b1b1b;
				font-size: 30rpx;
				font-weight: 500;
				height: 88rpx;
				flex: 1;
				align-items: center;
				justify-content: center;
				flex-direction: row;
				&.before::before {
					content: "";
					width: 2rpx;
					height: 50rpx;
					background-color: #e5e5e5;
				}
				label {
					flex: 1;
					flex-direction: column;
					&.active {
						color: #5487e5;
						&::after {
							content: "";
							margin-top: 8rpx;
							width: 100rpx;
							height: 8rpx;
							background-color: #5487e5;
							border-radius: 4rpx;
						}
					}
				}
			}
		}
		.scanCode-tips {
			font-size: 24rpx;
			text-align: center;
			margin-bottom: 18rpx;
		}

		.icon-location {
			width: 18rpx;
			height: 22rpx;
			margin-right: 18rpx;
		}
		.icon-location_black {
			width: 24rpx;
			height: 30rpx;
			margin-right: 12rpx;
		}
		.color-ff4a5b {
			color: #ff4a5b;
		}
		.color-459184 {
			color: #459184;
		}
		.pic-inCity {
			width: 100%;
			height: 100rpx;
		}

		.input {
			display: flex;
			align-items: center;
		}

		.in-city {
			position: relative;
			flex: 1;
			map {
				flex: 1;
				width: 100%;
			}

			.sos,
			.enableOrder,
			.shake {
				position: absolute;
				top: 30rpx;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				padding: 10rpx;

				text {
					letter-spacing: 0.1em;
					font-size: 20rpx;
					font-weight: 600;
				}
				image {
					width: 50rpx;
					height: 50rpx;
				}
				switch {
					transform: scale(0.7);
				}
			}
			.sos,
			.enableOrder {
				background-color: #fff;
				color: #666;
				box-shadow: #ccc 0 0 20rpx;
				border-radius: 10rpx;
				image {
					margin-bottom: 10rpx;
				}
			}
			.enableOrder {
				right: 30rpx;
			}
			.sos {
				left: 30rpx;
			}
			.shake {
				right: -6rpx;
				width: 110rpx;
				height: 110rpx;
				background-color: #5487e5;
				color: #fff;
				border-radius: 50%;
			}

			.choose-position {
				position: absolute;
				bottom: 0;
				background-color: #fff;
				width: 100%;
				border-radius: 20rpx 20rpx 0 0;

				.tips {
					position: absolute;
					top: -10rpx;
					left: 30rpx;
					transform: translateY(-100%);
					justify-content: flex-start;
					align-items: flex-start;

					.notice {
						margin: 12rpx 0;
						padding: 6rpx 10rpx;
						background-color: #fff;
						border-radius: 18rpx;
						.icon-medical {
							width: 22rpx;
							height: 22rpx;
						}
						text {
							margin-left: 0.3em;
							font-size: 22rpx;
						}
					}
					.journey {
						margin: 12rpx 0;
						padding: 6rpx 10rpx;
						background-color: #fff;
						border-radius: 18rpx;
						.icon-speaker {
							width: 19rpx;
							height: 17rpx;
						}
						text {
							margin-left: 0.5em;
							color: #5487e5;
							font-size: 20rpx;
						}
					}
				}

				.fee {
					font-size: 24rpx;
					text-align: center;
					margin-top: 30rpx;
				}
				.btn-confirm {
					line-height: 100rpx;
					background-color: #5487e5;
					border-radius: 10rpx;
					color: #fff;
					font-size: 32rpx;
					margin: 40rpx 30rpx;
				}
			}

			.orders {
				position: absolute;
				bottom: 0;
				background-color: #fff;
				width: 100%;
				border-radius: 20rpx 20rpx 0 0;
				padding: 30rpx 50rpx;
				.overview {
					.tips {
						font-size: 20rpx;
					}
				}
				.location-info {
					margin-top: 15rpx;

					.start-point,
					.destination {
						margin: 15rpx 0;
						&::before {
							content: "";
							width: 14rpx;
							height: 14rpx;
							margin-right: 18rpx;
							border-radius: 50%;
						}

						.name {
							font-size: 30rpx;
							color: #1b1b1b;
						}
						.address {
							color: #999;
							font-size: 20rpx;
						}
					}

					.start-point::before {
						background-color: #00ad84;
					}
					.destination::before {
						background-color: #4888e1;
					}
				}
				.btn-order {
					width: 120rpx;
					height: 120rpx;
					background-color: #4888e1;
					border: none;
					box-shadow: 0 0 12rpx #5296f5;
					border-radius: 50%;
					color: #fff;
					align-items: center;
					justify-content: center;
					font-size: 28rpx;
					line-height: 1.2;
					font-weight: 500;
					margin: 50rpx auto;
				}
				.order-type {
					font-size: 30rpx;
					color: #ff5500;
					text-align: center;
					margin-left: 12rpx;
				}

				.no-order,
				.has-order text {
					font-size: 28rpx;
					color: #333;
					text-align: center;
				}

				.has-order {
					flex-direction: row;
					justify-content: center;
					align-items: center;
					.icon-more {
						margin-left: 10rpx;
						width: 10rpx;
						height: 18rpx;
					}
				}
			}

			.shake-wrapper {
				border-radius: 20rpx;
				width: 80vw;
				background-color: #fff;
				overflow: hidden;
				.title {
					position: relative;
					height: 360rpx;
					padding-bottom: 150rpx;
					align-items: center;
					justify-content: center;
					image {
						width: 100%;
						height: 100%;
						position: absolute;
					}
					text {
						z-index: 1;
						color: #fdfaf9;
						font-weight: 500;
						font-size: 50rpx;
						text-shadow: 0 9rpx 10rpx rgba(113, 103, 247, 0.48);
					}
				}
				.content {
					z-index: 1;
					margin: -150rpx 50rpx 0;
					align-items: center;
					justify-content: center;
					background-color: #fff;
					box-shadow: 0 0 18rpx rgba(35, 24, 21, 0.11);
					border-radius: 20rpx;
					image {
						margin-top: -50rpx;
						width: 200rpx;
						height: 200rpx;
					}
					.describe {
						margin: 50rpx;
						align-items: center;
						.introduction {
							font-size: 30rpx;
							color: #333;
							font-weight: 500;
						}
						.waiting {
							margin-top: 20rpx;
							font-size: 24rpx;
							color: rgba(51, 51, 51, 0.5);
						}
					}
				}
				.btn-shake {
					margin: 50rpx;
					color: #fff;
					font-size: 28rpx;
					background-color: #5487e5;
					box-shadow: 0 6rpx 27rpx 0 rgba(32, 36, 161, 0.27);
					border-radius: 40rpx;
				}
			}
		}

		.choose-location {
			.start-point,
			.destination {
				padding: 0 30rpx;
				height: 110rpx;
				font-size: 22rpx;
				margin: 0 50rpx;
				border-radius: 20rpx;
				color: #1b1b1b;
				&::before {
					content: "";
					width: 14rpx;
					height: 14rpx;
					margin-right: 18rpx;
					border-radius: 50%;
				}
			}

			.start-point {
				.point {
					color: #5487e5;
					margin: 0 5rpx;
				}
				&::before {
					background-color: #17ad82;
				}
			}
			.destination {
				background-color: #eef3fc;

				&::before {
					background-color: #5487e5;
				}
			}
		}

		.intercity {
			> .routes {
				flex-direction: row;
				align-items: center;
				padding: 40rpx;
				border-bottom: #eee 10rpx solid;
				.place {
					flex: 1;
					overflow: hidden;
					justify-content: center;
					&::before {
						content: "";
						width: 14rpx;
						height: 14rpx;
						margin-right: 30rpx;
						border-radius: 50%;
					}
					&.green::before {
						background-color: #00ad84;
					}
					&.blue::before {
						background-color: #4888e1;
					}
					.location {
						max-width: 220rpx;
						overflow: hidden;
						text-align: center;
						.site {
							font-size: 36rpx;
							color: #1b1b1b;
						}
						.explain {
							font-size: 28rpx;
							color: #999;
						}
					}
				}
				.icon-transform {
					width: 63rpx;
					height: 63rpx;
					margin: 0 40rpx;
				}
			}
			> .options {
				margin-top: 30rpx;
				.option {
					flex-direction: row;
					align-items: center;
					padding: 0 30rpx;
					line-height: calc(100rpx / 3);
					font-size: 28rpx;
					border-bottom: 1rpx solid #e5e5e5;
					.ellipsis {
						flex: 1;
					}
					.title {
						display: block;
						width: 150rpx;
						color: #999;
						text-align-last: justify;
						text-align: justify;
						margin-right: 30rpx;

						&::after,
						&::before {
							content: "";
							display: inline-block;
							overflow: hidden;
							width: 100%;
						}
					}
					.number {
						flex-direction: row;
						align-items: baseline;
						.num {
							font-size: 28rpx;
							padding: 0 12rpx;
							width: 100rpx;
							text-align: center;
							color: #1b1b1b;
						}
						.reduce,
						.plus {
							font-size: 50rpx;
							padding: 0 18rpx;
						}
						.reduce {
							&::before {
								content: "-";
							}
							color: #999;
						}
						.plus {
							&::before {
								content: "+";
							}
							color: #5487e5;
						}
					}
					.input {
						font-size: 28rpx;
						height: 100%;
						flex: 1;
						padding: 0;
					}
					.time {
						flex: 1;
					}
				}
			}

			> .btn-start {
				margin: 50rpx 30rpx;
				background-color: #5487e5;
				color: #fff;
				border-radius: 10rpx;
			}

			.routes-popup {
				background-color: #fff;
				width: 88vw;
				border-radius: 10rpx;
				overflow: hidden;
				.title {
					background-color: #eee;
					color: #666;
					justify-content: space-between;
					font-size: 30rpx;
					padding: 20rpx 50rpx;
				}

				.search {
					margin: 40rpx 50rpx;
					background-color: #eee;
					border-radius: 30rpx;
					padding: 0 18rpx;
					.icon-search {
						width: 50rpx;
						height: 50rpx;
					}
					.input {
						flex: 1;
						color: #1b1b1b;
						font-size: 28rpx;
						padding: 12rpx;
					}
				}

				.options {
					margin-top: 10rpx;
					overflow: hidden;
					max-height: 40vh;
					.option {
						flex-direction: row;
						align-items: center;
						justify-content: space-between;
						padding: 30rpx 50rpx;
						border-bottom: 1rpx solid #e5e5e5;
						.routes-site {
							.site {
								font-size: 32rpx;
								color: #1b1b1b;
							}
							.icon-transform_blue {
								width: 33rpx;
								height: 33rpx;
								margin: 0 26rpx;
							}
						}
						.price {
							color: #ff0000;
							font-size: 32rpx;
						}
					}
				}
				.tips {
					overflow: hidden;
					padding: 30rpx;
					color: #666;
					font-size: 24rpx;
				}
			}
		}

		.icon-proclamation {
			width: 100vw;
		}

		.icon-close {
			margin: 70rpx auto;
			width: 74rpx;
			height: 74rpx;
		}
	}
</style>
